﻿/**************************************************************************************************

	NSurvey - The web survey and form engine
	Copyright (c) 2004, Thomas Zumbrunn. (http://www.nsurvey.org)

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

************************************************************************************************/
using System;
using System.Collections.Specialized;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Votations.NSurvey.DataAccess;
using Votations.NSurvey.Data;
using Votations.NSurvey.BusinessRules;
using Votations.NSurvey.WebAdmin.UserControls;
using Votations.NSurvey.Security;
using Microsoft.VisualBasic;

namespace Votations.NSurvey.WebAdmin
{
    /// <summary>
    /// Export survey data
    /// </summary>
    public partial class ExportData : PageBase
    {
        protected System.Web.UI.WebControls.Label CreationDateLabel;
        protected SurveyListControl SurveyList;
        public override string ActionCode
        {
            get
            {
                return "103";//报告
            }
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            SetupSecurity();
            LocalizePage();
            ScriptManager.GetCurrent(this).RegisterPostBackControl(ExportDataButton);
            ScriptManager.GetCurrent(this).RegisterPostBackControl(VoterExportXMLButton);
            if (!Page.IsPostBack)
            {
                SurveyList.SurveyId = SurveyId;
                SurveyList.BindDropDown();
                StartDateTextBox.Text = new DateTime(2003, 12, 31).ToShortDateString();
                EndDateTextBox.Text = DateTime.Now.ToShortDateString();
            }
        }

        private void SetupSecurity()
        {
            CheckRight(NSurveyRights.AccessExport, true);
        }

        private void LocalizePage()
        {
            FieldDelimiterLabel.Text = GetPageResource("FieldDelimiterLabel");
            TextDelimiterLabel.Text = GetPageResource("TextDelimiterLabel");
            ExportFromDateLabel.Text = GetPageResource("ExportFromDateLabel");
            ExportToDateLabel.Text = GetPageResource("ExportToDateLabel");
            FieldDelimiterLabel.Text = GetPageResource("FieldDelimiterLabel");
            FieldDelimiterLabel.Text = GetPageResource("FieldDelimiterLabel");
            SurveyExportTitle.Text = GetPageResource("SurveyExportTitle");
            ExportDataButton.Text = GetPageResource("ExportDataButton");
            VoterExportXMLButton.Text = GetPageResource("VoterExportXMLButton");
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {

        }
        #endregion


        /// <summary>
        /// Create and sends the CSV file to the client
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ExportCSVButton_Click(object sender, System.EventArgs e)
        {
            Response.Charset = "utf-8";
           // Response.ContentEncoding = System.Text.Encoding.Unicode; 
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=\"dataexport.csv\"");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
            DateTime startDate = (StartDateTextBox.Text == null && !Information.IsDate(StartDateTextBox.Text)) ?
                new DateTime(2004, 1, 1) : DateTime.Parse(StartDateTextBox.Text);
            DateTime endDate = (EndDateTextBox.Text == null && !Information.IsDate(EndDateTextBox.Text)) ?
                new DateTime(2004, 1, 1) : DateTime.Parse(EndDateTextBox.Text);

            Response.Write(ExportCSV());
            Response.End();
        }

        protected void VoterExportXMLButton_Click(object sender, System.EventArgs e)
        {
            DateTime startDate = (StartDateTextBox.Text == null && !Information.IsDate(StartDateTextBox.Text)) ?
                new DateTime(2004, 1, 1) : DateTime.Parse(StartDateTextBox.Text);
            DateTime endDate = (EndDateTextBox.Text == null && !Information.IsDate(EndDateTextBox.Text)) ?
                new DateTime(2004, 1, 1) : DateTime.Parse(EndDateTextBox.Text);

            Response.Charset = "utf-8";
            Response.ContentType = "application/octet-stream";

            Response.ContentType = "text/xml";
            Response.AddHeader("Content-Disposition", "attachment; filename=\"nsurvey_results" + SurveyId + ".xml\"");

            NSurveyVoter voterAnswers = new Voters().GetForExport(SurveyId, startDate, endDate);

            WebSecurityAddInCollection securityAddIns = WebSecurityAddInFactory.CreateWebSecurityAddInCollection(new SecurityAddIns().GetWebSecurityAddIns(SurveyId), ViewState);
            NameValueCollection addInVoterData;

            if (voterAnswers.Voter.Rows.Count > 0)
            {
                // Get security addins data if any available and get key name
                // to add it as new column to the voter table
                for (int i = 0; i < securityAddIns.Count; i++)
                {
                    addInVoterData = securityAddIns[i].GetAddInVoterData(voterAnswers.Voter[0].VoterID);
                    if (addInVoterData != null)
                    {
                        for (int j = 0; j < addInVoterData.Count; j++)
                        {
                            voterAnswers.Voter.Columns.Add(new DataColumn(addInVoterData.GetKey(j), typeof(string), null, System.Data.MappingType.Element));
                        }
                    }
                }

                for (int voterIndex = 0; voterIndex < voterAnswers.Voter.Rows.Count; voterIndex++)
                {
                    // Get security addins data if any available
                    for (int i = 0; i < securityAddIns.Count; i++)
                    {
                        addInVoterData =
                            securityAddIns[i].GetAddInVoterData(((NSurveyVoter.VoterRow)voterAnswers.Voter.Rows[voterIndex]).VoterID);
                        if (addInVoterData != null)
                        {
                            for (int j = 0; j < addInVoterData.Count; j++)
                            {
                                voterAnswers.Voter.Rows[voterIndex][addInVoterData.GetKey(j)] = addInVoterData[j];
                            }
                        }
                    }
                }
            }

            voterAnswers.WriteXml(Response.OutputStream, System.Data.XmlWriteMode.IgnoreSchema);

            Response.End();
        }

        private string ExportCSV()
        {
            DateTime startDate = (StartDateTextBox.Text == null && !Information.IsDate(StartDateTextBox.Text)) ?
                new DateTime(2004, 1, 1) : DateTime.Parse(StartDateTextBox.Text);
            DateTime endDate = (EndDateTextBox.Text == null && !Information.IsDate(EndDateTextBox.Text)) ?
                new DateTime(2004, 1, 1) : DateTime.Parse(EndDateTextBox.Text);

            System.Text.StringBuilder csvData = new System.Text.StringBuilder();
            bool scored = new Surveys().IsSurveyScored(SurveyId);

            // Get an instance of the voter DAL using the DALFactory
            CSVExportData csvExportData = new Voters().GetCSVExport(SurveyId, startDate, endDate);

            string textDelimiter = TextDelimiterTextBox.Text,
                fieldDelimiter = FieldDelimiterTextBox.Text;

            csvData.Append(textDelimiter + "VoterID" + textDelimiter);
            csvData.Append(fieldDelimiter + textDelimiter + "Start date" + textDelimiter);
            csvData.Append(fieldDelimiter + textDelimiter + "End date" + textDelimiter);
            csvData.Append(fieldDelimiter + textDelimiter + "IP" + textDelimiter);
            if (scored)
            {
                csvData.Append(fieldDelimiter + textDelimiter + "Score" + textDelimiter);
            }
            csvData.Append(fieldDelimiter + textDelimiter + "Email" + textDelimiter);
            csvData.Append(fieldDelimiter + textDelimiter + "UserName" + textDelimiter);
            csvData.Append(fieldDelimiter + textDelimiter + "CompanyName" + textDelimiter);

            // Build CSV header
            foreach (CSVExportData.ExportAnswersRow headerColumn in csvExportData.ExportAnswers.Rows)
            {
                csvData.Append(fieldDelimiter + textDelimiter + headerColumn.ColumnHeader.Replace(textDelimiter, textDelimiter + textDelimiter) + textDelimiter);
            }

            WebSecurityAddInCollection securityAddIns = WebSecurityAddInFactory.CreateWebSecurityAddInCollection(new SecurityAddIns().GetWebSecurityAddIns(SurveyId), ViewState);
            NameValueCollection addInVoterData;

            if (csvExportData.Voters.Rows.Count > 0)
            {
                // Get security addins data if any available and get key name
                // to add to the export header
                for (int i = 0; i < securityAddIns.Count; i++)
                {
                    addInVoterData = securityAddIns[i].GetAddInVoterData(csvExportData.Voters[0].VoterID);
                    if (addInVoterData != null)
                    {
                        for (int j = 0; j < addInVoterData.Count; j++)
                        {
                            csvData.Append(string.Format("{0}{1}{2}{1}",
                                fieldDelimiter, textDelimiter, addInVoterData.GetKey(j).Replace(textDelimiter, textDelimiter + textDelimiter)));
                        }
                    }
                }
            }

            foreach (CSVExportData.VotersRow voter in csvExportData.Voters.Rows)
            {
                csvData.Append(System.Environment.NewLine);
                csvData.Append(textDelimiter + voter.VoterID + textDelimiter);
                csvData.Append(fieldDelimiter + textDelimiter + voter.StartDate + textDelimiter);
                csvData.Append(fieldDelimiter + textDelimiter + voter.VoteDate + textDelimiter);
                csvData.Append(fieldDelimiter + textDelimiter + voter.IPSource + textDelimiter);
                if (scored)
                {
                    csvData.Append(fieldDelimiter + textDelimiter + voter.Score + textDelimiter);
                }
                csvData.Append(fieldDelimiter + textDelimiter + voter.Email + textDelimiter);

                if (voter.ContextUserName.Contains("~"))
                {
                    csvData.Append(fieldDelimiter + textDelimiter + voter.ContextUserName.Split('~')[0] + textDelimiter);
                    csvData.Append(fieldDelimiter + textDelimiter + voter.ContextUserName.Split('~')[1] + textDelimiter);
                }
                else
                {
                    csvData.Append(fieldDelimiter + textDelimiter + voter.ContextUserName + textDelimiter);
                    csvData.Append(fieldDelimiter + textDelimiter + "" + textDelimiter);
                }



                // reparse all answers to see which answer was answered or not by the voter
                foreach (CSVExportData.ExportAnswersRow headerColumn in csvExportData.ExportAnswers.Rows)
                {
                    // Check if the voter has answered
                    CSVExportData.VoterAnswersRow[] answer = (CSVExportData.VoterAnswersRow[])csvExportData.VoterAnswers.Select(string.Format("VoterID={0} AND AnswerID = {1}",
                        voter.VoterID, headerColumn.AnswerId));
                    if (answer.Length > 0)
                    {
                        if (answer[0].IsAnswerTextNull())
                        {
                            csvData.Append(fieldDelimiter + textDelimiter + 1 + textDelimiter);
                        }
                        else
                        {
                            csvData.Append(fieldDelimiter + textDelimiter + answer[0].AnswerText + textDelimiter);
                        }
                    }
                    else
                    {
                        csvData.Append(fieldDelimiter + textDelimiter + textDelimiter);
                    }
                }

                // Get security addins data if any available
                for (int i = 0; i < securityAddIns.Count; i++)
                {
                    addInVoterData = securityAddIns[i].GetAddInVoterData(voter.VoterID);
                    if (addInVoterData != null)
                    {
                        for (int j = 0; j < addInVoterData.Count; j++)
                        {
                            csvData.Append(string.Format("{0}{1}{2}{1}",
                                fieldDelimiter, textDelimiter, addInVoterData[j].Replace(textDelimiter, textDelimiter + textDelimiter)));
                        }
                    }
                }
            }

            return csvData.ToString();
        }

    }

}
